<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <component1></component1>
        <component2></component2>
    </div>
    <script src="vue.js"></script>
    <script>
        //所谓的eventBus其实就是一个空的Vue实例
        let eventBus = new Vue();
        var vm = new Vue({
            el:'#app',
            components:{
                component1:{
                    created(){
                        eventBus.$on('msg',this.handleMsg);
                    },
                    beforeDestroy(){
                        eventBus.$off('msg',this.handleMsg);
                    },
                    methods:{
                        sendMsg(){
                            eventBus.$emit('msg','这是一条来自于component1的消息'); 
                        },
                        handleMsg(msg){
                            console.log(msg)
                        }
                    },
                    template:`<button @click="sendMsg">sendMsg</button>`
                },
                component2:{
                    created(){
                        eventBus.$on('msg',this.handleMsg);
                    },
                    beforeDestroy(){
                        eventBus.$off('msg',this.handleMsg);
                    },
                    methods:{
                        sendMsg(){
                            eventBus.$emit('msg','这是一条来自于component2的消息'); 
                        },
                        handleMsg(msg){
                            console.log(msg)
                        }
                    },
                    template:`<button @click="sendMsg">sendMsg</button>`
                },
            }
           
        });
    </script>
</body>
</html>